package org.example.springboot.utils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Header;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Map;

public class JwtUtils {
  private static final long expireTime = 1000 * 3600;
  private static final SecretKey secretKey = generateSecretKey("wujingkai_wujingkai-wujingkai_wujingkai-wujingkai_wujingkai");

  public static String generateToken(SecretKey secretKey, Map<String, Object> claims) {
    return Jwts.builder()
        .claims(claims)
        .expiration(new Date(System.currentTimeMillis() + expireTime))
        .signWith(secretKey)
        .compact();

  }

  public static String generateToken() {
    return generateToken(secretKey, Map.of());

  }
  /**
   * 从字符串密钥生成SecretKey
   * @param secret 字符串密钥
   * @return SecretKey实例
   */
  public static SecretKey generateSecretKey(String secret) {
    return Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8));
  }

  public static Claims getPayload(String token) {
    return Jwts.parser()
        .verifyWith(secretKey)
        .build()
        .parseSignedClaims(token)
        .getPayload();
  }

  public static boolean invalidateOrExpiredToken(String token) {
    return isTokenExpired(getPayload(token));
  }

  public static boolean validateToken(String token) {
    return !invalidateOrExpiredToken(token);
  }

  /**
   * 提取JWT令牌中的头部信息
   * @param token JWT令牌
   * @return 头部信息
   */
  public static Header extractHeader(String token) {
    return Jwts.parser()
        .unsecured()
        .build()
        .parseSignedClaims(token)
        .getHeader();
  }

  /**
   * 检查令牌是否过期
   * @param claims 载荷信息
   * @return 如果过期返回true，否则返回false
   */
  public static boolean isTokenExpired(Claims claims) {
    return claims.getExpiration().before(new Date());
  }
}